from flask import Blueprint, jsonify, render_template
from flask_login import current_user, login_required
from ..baseapp import tasks_manager

bp_background_tasks = Blueprint(
    "background_tasks", __name__, url_prefix="/background_tasks"
)


@bp_background_tasks.route("/tasks", methods=["GET"])
@login_required
def get_all_tasks():
    """
    获取当前所有任务的状态信息。
    """
    tasks = tasks_manager.current_tasks
    task_list = [
        {
            "task_id": task_id,
            "status": task.status,
            "status_html": task.get_status_html(),
            "result": task.result,
            "display_name": task.get_display_name(),
            "started_at": task.created_at_ms,
            "finished_at": task.finished_at_ms,
        }
        for task_id, task in tasks.items()
        if task.user_id == current_user.id
    ]
    return jsonify(task_list)


@bp_background_tasks.route("/task/<task_id>", methods=["GET"])
def get_task_status(task_id: str):
    """
    获取指定任务的详细日志（status_html）。
    """
    try:
        task_status = tasks_manager.get_create_container_task_status(task_id)
        return jsonify(task_status)
    except KeyError as e:
        return jsonify({"error": str(e)}), 404


@bp_background_tasks.route("/view", methods=["GET"])
def background_tasks_page():
    """
    渲染 background_tasks.html 页面。
    """
    return render_template("background_tasks.html")
